# -*- coding: utf-8 -*-
import datetime
import json
import requests

from sqlalchemy import and_
from apps.stock import stock
from apps.stock.model import ClosedMarket, StockiIndex, StockTypes


# 0，抓取成功
# 1，重复抓取
# 2，休市
@stock.route('/index/insert', methods=['GET'])
def admin_department():
    """定义参数区域"""
    # 定义接口地址
    api_url = 'https://www.stcn.com/quotes/stock-info.html'

    """首先，要确定今天不是休市"""
    # 拿到今天的日期
    today = datetime.date.today()
    # 查询当天是否是节假日
    is_closed = ClosedMarket.query.filter(ClosedMarket.date == today).first()
    # 如果今天是法定节假日，提示休市
    if is_closed and is_closed.is_closed is True:
        response = {
            'code': 2,
            'msg': 'today is legal holidays,market is closed.'
        }
        return json.dumps(response, ensure_ascii=False)
    # 如果今天是周末，提示休市
    if today.weekday() >= 5:
        print(22)
        response = {
            'code': 2,
            'msg': 'today is weekend, market is closed.'
        }
        return json.dumps(response, ensure_ascii=False)

    """获取指数代码，爬取指数数据并记录日志"""
    # 拿到指数代码
    index_ids = StockTypes.query.filter().all()
    logs = []  # 爬取日志
    if index_ids:
        # 轮询取出指数代码，去爬取指数
        for index_id in index_ids:
            # 封装请求参数，准备get请求数据
            params = {
                'stock_code': index_id.type_code
            }
            content = requests.get(api_url, params=params)
            # 获取到当天的指数数据
            data = json.loads(content.text)
            is_today_index = StockiIndex.query.filter(and_(
                StockiIndex.index_type == index_id.type_id,
                StockiIndex.date == today.strftime('%Y-%m-%d')
            )).first()
            # 判断是否数据库已存在当日指数数据
            if is_today_index:
                logs.append({
                    'code': 1,
                    'data': index_id.type_code,
                    'msg': 'today index is already.'
                })
                continue
            # 组装插入当前字数数据记录
            today_index = {
                'stop_price': data.get('data').get('cv'),
                'start_price': data.get('data').get('open'),
                'max_price': data.get('data').get('high'),
                'min_price': data.get('data').get('low'),
                'date': today.strftime('%Y-%m-%d'),
                'index_type': index_id.type_id
            }
            print(today_index)
            new_index = StockiIndex(today_index)
            new_index.create()
            logs.append({
                'code': 0,
                'index_code': index_id.type_code,
                'msg': 'today index created.'
            })
        # 爬取完成后，返回爬取日志。
        response = {
                'code': 0,
                'msg': 'success.',
                'data': logs
            }
        print(response)
        return json.dumps(response, ensure_ascii=False)

    # 如果没拿到代码
    response = {
        'code': 3,
        'msg': 'Stock code not in Mysql！'
    }
    return json.dumps(response, ensure_ascii=False)
